<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { getTopMenu, initRouter } from "@/router/utils";
import { avatar, banner } from "./utils/static";
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { useUserStoreHook } from "@/store/modules/user";

import LoginRegister from "./components/LoginRegister.vue";
defineOptions({
  name: "Login"
});
const isLogin = ref(true);
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
const { initStorage } = useLayout();
initStorage();

const { overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title } = useNav();
// username: "admin",
// password: "admin123"
const ruleForm = reactive({
  username: "",
  password: "",
  otpCode: ""
});

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      loading.value = true;
      try {
        await useUserStoreHook().loginByUsername(ruleForm);
        await initRouter();
        router.push(getTopMenu(true).path);
        message("登录成功", { type: "success" });
      } catch (e) {
        console.log(e);
      } finally {
        loading.value = false;
      }
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (["Enter", "NumpadEnter"].includes(code)) {
    onLogin(ruleFormRef.value);
  }
}

const back = () => {
  isLogin.value = true;
};
onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <!-- <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      /> -->
    </div>
    <div class="login-container">
      <div class="login-box">
        <div class="title-logo">
          <div>
            <img :src="avatar" alt="" />
            <h2 class="outline-none">{{ title }}</h2>
          </div>
        </div>
        <div class="login-form">
          <Motion :delay="100">
            <div class="title-login">登录您的账号</div>
          </Motion>
          <el-form
            v-if="isLogin"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  placeholder="输入您的账号"
                  class="w-full"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  placeholder="输入您的密码"
                  class="w-full"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="200">
              <el-form-item prop="otpCode">
                <el-input
                  v-model="ruleForm.otpCode"
                  clearable
                  placeholder="输入您的otpCode"
                  class="w-full"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-form-item>
                <el-button
                  class="w-full mt-4"
                  size="large"
                  type="primary"
                  :loading="loading"
                  @click="onLogin(ruleFormRef)"
                >
                  登录
                </el-button>
              </el-form-item>
            </Motion>
            <Motion :delay="300">
              <div>
                <span>还没有账号？</span>
                <el-button type="primary" link @click="isLogin = false">
                  去注册
                </el-button>
              </div>
            </Motion>
          </el-form>
          <LoginRegister v-if="!isLogin" @back="back" />
        </div>
      </div>
      <div class="img">
        <img :src="banner" class="banner" alt="" />
        <!-- <div class="login-img">
          <img class="vip-img" src="@/assets/login/vip.png" alt="" />
          <img class="icon-img" src="@/assets/login/icon.png" alt="" />
          <el-tag type="primary" effect="plain">
            推荐朋友请联系
            <el-link type="success">@Blao8</el-link>
          </el-tag>
        </div> -->
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
.login-box {
  position: relative;
}
.title-logo {
  width: 100%;
  position: absolute;
  display: flex;
  justify-content: center;
  top: 2em;
  div {
    width: 360px;
    display: flex;
    align-items: center;
    gap: 10px;
    img {
      width: 28px;
    }
    h2 {
      font-weight: bolder;
    }
  }
}
.img {
  height: 100vh;
  .banner {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}
.title-login {
  font-size: 22px;
  font-weight: bold;
  text-align: left;
  margin-bottom: 16px;
  color: var(--pure-theme-sub-menu-active-text);
}
.login-img {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  .el-link {
    font-size: 12px;
  }
  .icon-img {
    width: 500px;
  }
  .vip-img {
    width: 50%;
    position: absolute;
    top: -34%;
    z-index: 1;
  }
}
.el-input {
  :deep(.el-input__wrapper) {
    background-color: rgb(250, 250, 250);
  }
}
</style>
